<template>
  <div class="goods-params">
    <!-- 标题 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- alert 提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="cate-cascader">
        <el-col>
          <span>请选择商品分类: </span>
          <el-cascader
            v-model="cascader.value"
            :options="goodsList"
            :props="cascader.props"
            @change="handleCascaderChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- 菜单 -->
      <el-tabs
        v-model="tabs.activeName"
        @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                @click="openAddParamsDialog"
                :disabled="isAddBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <!-- 表格 -->
          <el-table
            :data="manyParamsList"
            border
            stripe>
            <el-table-column type="expand" v-slot="data">
              <el-tag
              v-for="(value, index) in data.row.attr_vals"
              :key="data.row.attr_id + index"
              closable
              @close="removeTag(data.row, index)">{{ value }}</el-tag>
              <el-input
                class="input-new-tag"
                v-if="addTag.addTagInputVisible"
                v-model="addTag.inputValue"
                ref="addTagRef"
                size="small"
                @keyup.enter.native="handleAddTagInputConfirm(data.row)"
                @blur="handleAddTagInputConfirm(data.row)"></el-input>
              <el-button
                v-else class="button-new-tag"
                size="small"
                @click="showAddTagInput">+ New Tag</el-button>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" v-slot="data">
              <!-- 编辑参数按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="openEditParamsDialog(data.row)">编辑</el-button>
              <!-- 删除参数按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="removeParams(data.row.attr_id)">删除</el-button>
              <el-button style="display: none">{{ data.row }}</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性 -->
          <el-row>
            <el-col>
              <el-button
                type="primary"
                @click="openAddParamsDialog"
                :disabled="isAddBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <!-- 表格 -->
          <el-table
            :data="onlyParamsList"
            border
            stripe>
            <el-table-column type="expand" v-slot="data">
              <el-tag
              v-for="(value, index) in data.row.attr_vals"
              :key="data.row.attr_id + index">{{ value }}</el-tag>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" v-slot="data">
              <!-- 编辑参数按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="openEditParamsDialog(data.row)">编辑</el-button>
              <!-- 删除参数按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="removeParams(data.row.attr_id)">删除</el-button>
              <el-button style="display: none">{{ data.row }}</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + getTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="closeAddParamsDialog">
      <el-form
        label-width="80px"
        :model="addParamsForm"
        :rules="addPramasFormRules"
        ref="addParamsFormRef">
        <el-form-item :label="getTitle" prop="attr_name">
          <el-input
            v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddParams">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'添加' + getTitle"
      :visible.sync="editParamsDialogVisivle"
      width="50%"
      @close="closeEditParamsDialog">
      <el-form
        label-width="80px"
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef">
        <el-form-item :label="this.getTitle" prop="attr_name">
          <el-input
            v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisivle = false">取 消</el-button>
        <el-button type="primary" @click="submitEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodsParams',
  data () {
    return {
      // 分类列表数据
      goodsList: [],
      // 动态参数列表
      manyParamsList: [],
      // 静态参数列表
      onlyParamsList: [],
      cascader: {
        // 选中的值
        value: '',
        // 第三级值
        currentValue: '',
        // 配置
        props: {
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        }
      },
      // 参数目录
      tabs: {
        activeName: 'many'
      },
      /* 弹出添加参数对话框 */
      addParamsDialogVisible: false,
      /* 添加参数对话框表单 */
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数规则
      addPramasFormRules: {
        attr_name: [
          { required: true, message: '请填写参数', trigger: 'blur' }
        ]
      },
      /* 弹出编辑参数对话框 */
      editParamsDialogVisivle: false,
      /* 编辑参数对话框表单 */
      editParamsForm: {
        attr_name: '',
        attr_id: null
      },
      // 编辑参数规则
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请填写参数', trigger: 'blur' }
        ]
      },
      // 添加参数标签
      addTag: {
        inputValue: '',
        addTagInputVisible: false
      }
    }
  },
  created () {
    this.getGoodsList()
    // this.getParamsList()
  },
  computed: {
    // 1. 根据tabs点击获取动态还是静态
    getTitle () {
      if (this.tabs.activeName === 'many') {
        return '动态参数'
      } else if (this.tabs.activeName === 'only') {
        return '静态属性'
      }
      return false
    },
    // 2. 判断button的disabled
    isAddBtnDisabled () {
      if (!this.cascader.currentValue) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    // 1. 获取商品分类目录数据
    async getGoodsList () {
      const { data: res } = await this.$http.get('/categories', {
        params: {
          type: 3
        }
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      // 获取成功
      this.goodsList = res.data
    },
    // 2. 获取分类参数
    async getParamsList () {
      // 判断是否选择了分类
      if (!this.cascader.currentValue) {
        return this.$message.info('请选择分类')
      }
      const { data: res } = await this.$http.get(`/categories/${this.cascader.currentValue}/attributes`, {
        params: {
          sel: this.tabs.activeName
        }
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        // 判断是否为空数组不然渲染成空标签
        if (!item.attr_vals) {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(',')
        }
      })

      if (this.tabs.activeName === 'many') {
        this.manyParamsList = res.data
      } else if (this.tabs.activeName === 'only') {
        this.onlyParamsList = res.data
      }
      // 查看获取的值
      console.log(res.data)
    },
    // 3. 处理级联表点击事件
    handleCascaderChange (value) {
      if (value.length !== 3) return
      this.cascader.currentValue = value[value.length - 1]
      this.getParamsList()
    },
    // 4. 点击tabs处理函数
    handleTabClick () {
      console.log(this.tabs)
      this.getParamsList()
    },
    // 5. 打开添加参数dialog
    openAddParamsDialog () {
      this.addParamsDialogVisible = true
    },
    // 6. 关闭添加参数dialog
    closeAddParamsDialog () {
      this.$refs.addParamsFormRef.resetFields()
    },
    // 7. 确认添加参数
    submitAddParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`/categories/${this.cascader.currentValue}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.tabs.activeName
        })
        console.log(res)
        // 刷新数据
        this.getParamsList()
        this.addParamsDialogVisible = false
      })
    },
    // 8. 删除参数
    async removeParams (attrid) {
      // 获取点击结果
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        type: 'warning'
      }).catch(err => err)
      // console.log(result)
      if (result === 'cancel') {
        return this.$message.info('已取消删除操作')
      } else if (result === 'confirm') {
        const { data: res } = await this.$http.delete(`/categories/${this.cascader.currentValue}/attributes/${attrid}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('删除参数失败')
        }
        this.$message.success('删除参数成功')
        this.getParamsList()
      }
    },
    // 9. 打开编辑参数对话框
    openEditParamsDialog (value) {
      console.log(value)
      this.editParamsForm.attr_name = value.attr_name
      this.editParamsForm.attr_id = value.attr_id
      this.editParamsDialogVisivle = true
    },
    // 10. 关闭编辑参数对话框
    closeEditParamsDialog () {
      console.log('关闭对话框')
      this.$refs.editParamsFormRef.resetFields()
      this.editParamsForm.attr_name = ''
      this.editParamsForm.attr_id = null
    },
    // 11. 提交编辑参数
    async submitEditParams () {
      console.log(111)
      this.$refs.editParamsFormRef.validate(valid => {
        if (!valid) return false
      })
      // 因为不涉及到标签 所以不用添加attr_vals参数
      const { data: res } = await this.$http.put(`categories/${this.cascader.currentValue}/attributes/${this.editParamsForm.attr_id}`, {
        attr_name: this.editParamsForm.attr_name,
        attr_sel: this.tabs.activeName
      })
      if (res.meta.status !== 200) {
        return this.$messgae.error('修改参数失败')
      }
      // 修改参数成功
      this.getParamsList()
      // 关闭对话框
      this.editParamsDialogVisivle = false
    },
    // 12. 点击在参数增加标签按钮
    showAddTagInput () {
      this.addTag.addTagInputVisible = true
      // 自动聚焦
      this.$nextTick(() => {
        this.$refs.addTagRef.$refs.input.focus()
      })
    },
    // 13. 处理添加参数标签处理函数
    async handleAddTagInputConfirm (value) {
      // 为空则关闭dialog
      if (!this.addTag.inputValue.trim()) {
        this.addTag.addTagInputVisible = false
        this.addTag.inputValue = ''
        return false
      }
      // 使用value.attr.vals变成传送给服务器的string格式
      value.attr_vals.push(this.addTag.inputValue)
      console.log(value.attr_vals)
      // 发送请求
      const { data: res } = await this.$http.put(`categories/${this.cascader.currentValue}/attributes/${value.attr_id}`, {
        attr_name: value.attr_name,
        attr_sel: this.tabs.activeName,
        attr_vals: value.attr_vals.join()
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('提交参数失败')
      }
      this.$message.success('提交参数成功')
      // 重置其属性
      this.addTag.addTagInputVisible = false
      this.addTag.inputValue = ''
    },
    // 14. 删除标签
    async removeTag (value, index) {
      // 弹出确认框
      const result = await this.$confirm('你确定要删除该标签吗', '提示', {
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return false
      // 删除指定tag
      value.attr_vals.splice(index, 1)
      const { data: res } = await this.$http.put(`categories/${this.cascader.currentValue}/attributes/${value.attr_id}`, {
        attr_name: value.attr_name,
        attr_sel: this.tabs.activeName,
        // 格式化
        attr_vals: value.attr_vals.join()
      })
      if (res.meta.status !== 200) {
        return this.$message.error('删除标签失败')
      }
      // 删除标签成功
      this.$message.success('删除标签成功')
    }
  }
}
</script>

<style scoped lang="less">
.goods-params {
  > .el-breadcrumb {
    font-size: 12px;
  }
  > .el-card {
    margin-top: 15px;
    .cate-cascader {
      margin-top: 15px;
      font-size: 14px;
    }
    .el-tabs {
      margin-top: 12px;
      .el-table {
        margin-top: 15px;
        .el-tag {
          margin: 10px;
        }
      }
    }
  }
}
</style>
